<?php

// +----------------------------------------------------------------------
// | 版权所有 2017-2027 云南环拓科技有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.yn123.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// | 注意：  这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用,
// |        不允许对程序代码以任何形式任何目的的再发布。
// +----------------------------------------------------------------------
// | Author: feraner <feraner@163.com> 
// | Date: 2019/9/29
// +----------------------------------------------------------------------

namespace app\index\controller;

use app\common\facade\Arr;
use app\common\facade\Help;
use app\common\services\UserService;
use app\wechat\service\WechatService;
use think\App;
use think\Controller;
use think\facade\Config;

/**
 * 微信公共控制器 [处理微信用户自动授权登录]
 * Class WechatBase
 * @package app\index\controller
 * @author feraner<feraner@163.com>
 * @date 2019/9/29
 */
class WechatBase extends Controller
{

    /**
     * WechatBase constructor.
     *
     * @param App|null $app
     *
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function __construct(App $app = null)
    {
        parent::__construct($app);
        if (Help::isWechat()) {
            $this->autoLogin();
        }
        $this->assign('inWechat', Help::isWechat());
        $this->assign('baseHost', Config::get('api_host_name'));
        $this->assign('appName', sysconf('app_name'));

    }


    /**
     * 微信自动登录流程
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function autoLogin()
    {
        if (!session('user')) {
            $code = $this->request->param('code', null);
            $state = $this->request->param('state', null);
            if ($code && $state == cookie('state')) {
                $result = WechatService::WeChatOauth()->getOauthAccessToken();
                if(Arr::has($result, 'access_token') && Arr::has($result, 'openid')) {
                    $userInfo = WechatService::WeChatOauth()->getUserInfo(
                        Arr::get($result, 'access_token'),
                        Arr::get($result, 'openid')
                    );
                    if (Arr::get($userInfo, 'openid')) {
                        try {
                            if ($user = (new UserService())->updateUser($userInfo)) {
                                //记录用户信息
                                session('user', $user);
                                session('userId', Arr::get($user, 'id'));
                                cookie('state', null);
                            }
                        } catch (\Exception $e) {
                            $this->error($e->getMessage());
                        }
                    }
                } else {
                    $this->error('授权失败，请重新授权！');
                }
                $this->_deleteOauthParams();
            } else {
                $redirectUrl = $this->request->url(true);
                cookie('state' , rand(100000 , 999999));
                $authUrl = WechatService::WeChatOauth()->getOauthRedirect($redirectUrl, cookie('state'), 'snsapi_userinfo');
                $this->redirect($authUrl);
            }
        }
    }


    /**
     * 将微信网页授权后的参数剔除掉
     */
    private function _deleteOauthParams()
    {
        if( $this->request->param('code') && $this->request->param('state') ) {
            $url = $this->request->url(true);
            $reg = '/\?code.*&state.*$/';
            $url = preg_replace($reg , '' , $url);
            $this->redirect($url);
        }
    }


    /**
     * wechat js SDK config
     * @param $url
     *
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     */
    public function assignJsSign($url)
    {
        $wechatJsSDK = [
            'debug'     => false,
            "appId"     => '',
            "nonceStr"  => '',
            "timestamp" => '',
            "signature" => '',
            'jsApiList' => []
        ];
        if (Help::isWechat()) {
            $wechatJsSDK = WechatService::WeChatScript()->getJsSign($url);
        }

        $this->assign('wechatJsSDK', $wechatJsSDK);
    }



}
